#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：turbo 
@File    ：utils.py
@Author  ：赵加响
@Date    ：2023/5/4 14:59 
@Desc    ：
"""
import datetime
import hashlib
import os

from constants import PATH_LEVEL


def create_folder(upload_path):
    if not os.path.exists(upload_path):
        os.makedirs(upload_path)


def create_instance(instance, request):
    user = request.user
    now = datetime.datetime.now()
    path = request.path_info
    method = request.method

    instance.created = user
    instance.created_date = now
    instance.created_program = method + ' -> ' + path
    instance.updated = user
    instance.updated_date = now
    instance.updated_program = method + ' -> ' + path


def update_instance(instance, request):
    user = request.user
    now = datetime.datetime.now()
    path = request.path_info
    method = request.method

    instance.updated = user
    instance.updated_date = now
    instance.updated_program = method + ' -> ' + path


def update_set(request, create=False):
    user = request.user
    now = datetime.datetime.now()
    path = request.path_info
    method = request.method

    if create:
        return {'created': user, 'created_date': now, 'created_program': method + ' -> ' + path,
                'updated': user, 'updated_date': now, 'updated_program': method + ' -> ' + path}
    else:
        return {'updated': user, 'updated_date': now, 'updated_program': method + ' -> ' + path}


def upload_file_save_rename_as_md5(file, path, marker, levels=PATH_LEVEL):
    """
    重命名文件并保存到指定的目录
    Args:
        file: 原始文件
        path: 目标路径
        marker: MD5命名标记
        levels: 新建文件夹层数，会以新文件名的前levels位来生成文件夹

    Returns: 原始文件名、MD5文件名
    """
    original_filename = file.name
    extension = original_filename.split('.')[-1]
    filename = hashlib.md5(f"{str(marker)}".encode()).hexdigest()
    filename = filename + '.' + extension
    file_path = path.joinpath('/'.join(filename[:levels]))
    if not file_path.exists():
        file_path.mkdir(parents=True)

    with open(file_path.joinpath(filename), 'wb') as f:
        for i in file.chunks():
            f.write(i)

    return original_filename, filename
